package com.geely.design.pattern.behavioral.responsibilitychain.v2;

import java.util.ArrayList;
import java.util.List;

public class FilterChain{
    // 第一步: 收集Filter - 将所有的Filter都添加到FilterChain的filterList里面
    List<Filter> filterList = new ArrayList<Filter>();
    private int index;

    void addFilter(Filter filter){
        filterList.add(filter);
    }

    void doFilter(String s1,String s2) {
        if (index == filterList.size()) {
            return;
        }
        Filter filter = filterList.get(index);
        index++;
        // 第二步: 依次调用Filter - 并且将当前的执行链交给该Filter,
        //                        那么,控制权就交到该Filter手里了,
        //                        由该Filter决定是否还继续执行FilterChain中接下来的Filter
        filter.intercept(s1,s2,this);

    }

    public static void main(String[] args) {
        FilterChain filterChain = new FilterChain();
        filterChain.addFilter(new Filter1());
        filterChain.addFilter(new Filter2());
        filterChain.addFilter(new Filter3());
        filterChain.doFilter("请求","响应");
    }

}

class Filter1 implements Filter{

    @Override
    public void intercept(String req, String resp, FilterChain filterChain) {
        System.out.println("filter1..."+req);
        filterChain.doFilter(req, resp);
        System.out.println("filter1..."+resp);
    }
}

class Filter2 implements Filter{

    @Override
    public void intercept(String req, String resp, FilterChain filterChain) {
        System.out.println("filter2..."+req);
        filterChain.doFilter(req, resp);
        System.out.println("filter2..."+resp);
    }
}

class Filter3 implements Filter{

    @Override
    public void intercept(String req, String resp, FilterChain filterChain) {
        System.out.println("filter3..."+req);
        filterChain.doFilter(req, resp);
        System.out.println("filter3..."+resp);
    }
}
